<?php
// http://oauth.vk.com/authorize?client_id=3360696&scope=2097151&response_type=token&redirect_uri=blank.html
$token_download = '2'; // откуда дампить
$token_upload  = '';  // куда дампить
// if ($token_download==''){
// 	PrintLog("Make sure you enter token",true);
// }

class NetworkException extends Exception{

}

interface LogerWriter{
	function printLog($text, $warn=false);
}

class ConsoleLogger implements LogerWriter{
	public function printLog($text,$warn=false){
		if($warn) {
			echo "Fatal error [$text]" . PHP_EOL;
			exit(1);
		} else {
			// echo @date('[H:i:s]: ') . iconv('utf-8', 'cp866', $text) . PHP_EOL;
			echo @date('[H:i:s]: ') . iconv('utf-8', 'cp1251', $text) . PHP_EOL;
		}
	}
}

$log = new ConsoleLogger();
class VKAPI{
	private $token;
	private $logger;
	

	function __construct($token){
		if (empty($token)) {
			throw new InvalidArgumentException("token can not be empty");
		}
		$this->token = $token;
		$this->logger = new ConsoleLogger();
		// TODO: add users.get method call for validating token
	}
	
	public function log($text,$warn=false){
		$this->logger->printLog($text,$warn);
	}
	
	public function getContent($url, $cookie = false, $headers = false, $post = false, $proxy = false, $referer = false) {
		$this->log("tets");
		$ch = curl_init($url);

		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HEADER, $headers);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
		curl_setopt($ch, CURLOPT_COOKIE, $cookie);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1');

		if($referer) {
			curl_setopt($ch, CURLOPT_REFERER, $referer);
		}

		if(strpos($url, 'https')!==FALSE) {
			curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
		}

		if($proxy) {
			curl_setopt($ch, CURLOPT_PROXY, $proxy);
		}

		if ($post) {
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
		}

		$response = curl_exec ($ch);


		if(!curl_errno($ch)){
			$info = curl_getinfo($ch);
		} else {
			PrintLog( 'Curl error: ' . curl_error($ch));
			PrintLog( 'data: ' . $url);
			throw new NetworkException(curl_error($ch));
		}

		curl_close($ch);
		return $response;

	}
	
	function apiQuery($method, $param = false) {
		$data = "";
		$this->log("in apiQuery");
		if($param) {
			foreach ($param as $key => $val) {
				$data .= "&$key=" . urlencode($val);
			}
		}
		$url = "https://api.vk.com/method/$method?access_token={$this->token}$data";
		$this->log($url);
		return json_decode($this->getContent($url), true);
	}
}

$fromUser = new VKAPI($token_download);
echo iconv('utf-8', 'cp1251', print_r($fromUser->apiQuery("users.get"),true));
// audio.get
echo iconv('utf-8', 'cp1251//IGNORE', print_r($fromUser->apiQuery("audio.get",array("offset"=>0,"count"=>1000)),true));

$log->printLog("create base");
// [aid] = 138807669
/* [456] 
 // audio.1.txt (1000 entries max)
 {
 	"albumDirName": "Orjan Nilsen"
 	, "vkListName": "▲▲▲:Orjan Nilsen"
 	, "album": 13471319
 	, "tracks":[
 		 {
		  "fileName": "Orjan Nilsen – Le Tour De Trance.mp3"
		  ,"vkname": "▲▲▲:Orjan Nilsen – Le Tour De Trance"
		  ,"aid": 138807669
		 },
		 {
		  "fileName": "Orjan Nilsen – La Guitarra  (Original Mix).mp3"
		  ,"vkname": "▲▲▲:Orjan Nilsen – La Guitarra  (Original Mix)"
		  ,"aid": 175105012
		 }
		 ....
 	]
 }
 
 index building: $index['localfilename'] = $vkfilename;
 $counter = 0;
 while(!isset($index[$localfilename])){
 	 if (!isset($index[$localfilename])){
	 	$index[$localfilename] = $vkfilename;
	 } else {
	  	$counter++;
	 	$localfilename.".$counter"
	 }
 }
 my - audio
 my - audio.1
 my - audio.2
 ...

 
 
 */
die("test to here");

function DownloadMedia($type, $url, $dir, $file_name, $statusMessage='ok')
{
	$dir = iconv('utf-8', 'windows-1251', $dir);
	//$file_name = iconv('utf-8', 'windows-1251', $file_name);
	
	//if(strlen($file_name) < 3)
	//{
	//	$file_name = md5(date());
	//}
	
	if(!is_dir(__DIR__ . "\\" . $dir))
	{
		mkdir(__DIR__ . "\\" . $dir, 777);

	}
	
	$media = array('img' => '.jpg', 'mp3' => '.mp3', 'docs' => '');

	$fp = fopen("$dir/$file_name" . $media[$type], 'w');
	fwrite($fp, file_get_contents($url)); 
        fclose($fp);

        PrintLog("download [$file_name" . $media[$type] . "][".$statusMessage."]");
}

function GetPhotoSize($info)
{
	if(isset($info['src_xxbig']))
	{
		$size = 'src_xxbig';
	}
	elseif(isset($info['src_xbig']))
	{
		$size = 'src_xbig';
	}
	else
	{
		$size = 'src_big';
	}
	
	return $size;
}

function PhotosCount(){
	PrintLog("get all photo count...");
	$count = 0;
	$albums = ApiQuery('photos.getAlbums');
	for($i = 0; $i < count($albums['response']); $i++){
		$count+=$albums['response'][$i]['size'];
	}
	PrintLog("found ".$count." photos");
	return $count;
}


function AlbumsDump($howMany)
{
	
	PrintLog("get albums...");
	$albums = ApiQuery('photos.getAlbums');
	PrintLog("found " . count($albums['response']) . " albums...");

	$localCounter = 0;
	for($i = 0; $i < count($albums['response']); $i++)
	{
		PrintLog("get photos list...");
		$photos_list = ApiQuery('photos.get', array('uid' => $albums['response'][$i]['owner_id'], 'aid' => $albums['response'][$i]['aid']));
		PrintLog("found " . count($photos_list['response']) . " photos...");

		for($j = 0; $j < count($photos_list['response']); $j++)
		{
			
			$status = ($localCounter++)." of ".$howMany;
			$size = GetPhotoSize($photos_list['response'][$j]);
			DownloadMedia('img', $photos_list['response'][$j][$size], $albums['response'][$i]['title'], $photos_list['response'][$j]['pid'],$status);
		}
	}
}


function AvatarsCount(){
	$avatars = ApiQuery('photos.getProfile');
	return (isset($avatars['response']))?count($avatars['response']):0;
}

function AvatarsDump($count)
{
	PrintLog("get avatars..");
	$avatars = ApiQuery('photos.getProfile');
	PrintLog("found " . count($avatars['response']) . " avatars...");
	$localCount = 0;
	for($i = 0; $i < count($avatars['response']); $i++)
	{
		$debugMessage = $localCount." of ".$count;
		$size = GetPhotoSize($avatars['response'][$i]);
		DownloadMedia('img', $avatars['response'][$i][$size], 'avatars', $avatars['response'][$i]['pid'], $debugMessage);
	}
}

function AudioDump()
{
	PrintLog("get audios...");
	$audios_list = ApiQuery('audio.get');
	PrintLog("found " . count($audios_list['response']) . " tracks...");
	
	for($i = 0; $i < count($audios_list['response']); $i++)
	{
		DownloadMedia('mp3', $audios_list['response'][$i]['url'], 'audio', $audios_list['response'][$i]['artist'] . ' - ' . $audios_list['response'][$i]['title']);
	}
}

function DocsDump()
{
	PrintLog("get docs...");
	$docs_list = ApiQuery('docs.get');
	PrintLog("found " . count($docs_list['response']) . " docs...");

	for ($i = 0; $i < count($docs_list['response']); $i++)
	{
		DownloadMedia('docs', $docs_list['response'][$i]['url'], 'docs', $docs_list['response'][$i]['title']);
	}
}

function MyScanDir($dir) // заебался хуячить array_splice, вынес в функцию
{
	$files = scandir($dir);
	$files = array_diff($files, array('.', '..'));
	// $data = array_splice($files, 2, count($files)); говно твой array_splice
	return $files;
}

function ScanDump()
{
	$home_dir = MyScanDir(__DIR__);
	$result = array();
	
	PrintLog("scaning " . __DIR__);
	
	foreach($home_dir as $folder)
	{
		if($folder == 'avatars')
			continue;
			
		if(is_dir($folder))
		{	
			PrintLog("scaning " . __DIR__ . "\\$folder");
			$photos_name = MyScanDir(__DIR__ . '\\' . $folder);
			PrintLog("found " . count($photos_name) . " photos...");
			
			foreach($photos_name as $path)
			{
				$result[$folder][] = __DIR__ . '\\' . $folder . '\\' . $path;
			}
		}
	}
	
	return $result;
}

function LoadPhotoDump()
{
	PrintLog("scanning directory for photo...");
	$albums_list = ScanDump();
	PrintLog("found " . count($albums_list) . " albums...");
	
	foreach ($albums_list as $title => $photos_list)
	{
		PrintLog("create album...");
		$create_album = ApiQuery('photos.createAlbum', array('title' => iconv('windows-1251', 'utf-8', $title), 'privacy' => 3, 'comment_privacy' => 3, 'description' => 'Created by VK Media Dumper (c) NRO'));
		PrintLog("album [$title] created");
		
		foreach ($photos_list as $photo)
		{
			PrintLog("get upload url...");
			$get_upload_url = ApiQuery('photos.getUploadServer', array('aid' => $create_album['response']['aid']));
			PrintLog("album for download: " . "http://vk.com/album" . $get_upload_url['response']['mid'] . '_' . $get_upload_url['response']['aid']);
			
			PrintLog("upload $photo");
			$get_save_param = json_decode(GetContent($get_upload_url['response']['upload_url'], 0, 0, array('file1' => '@' . $photo)), true);
			PrintLog("upload is successful...");
			
			PrintLog("save photo...");
			$photo_save = ApiQuery('photos.save', array('aid' => $get_save_param['aid'], 'server' => $get_save_param['server'], 'photos_list' => $get_save_param['photos_list'], 'hash' => $get_save_param['hash']));
			PrintLog("save is successful [" . $photo_save['response'][0]['src_big'] . "]");
		}
	}
}

function LoadAudioDump()
{
	PrintLog("scanin for audio...");
	$audio_list = MyScanDir(__DIR__ . '\\audio');
	PrintLog("found " . count($audio_list) . " tracks...");
	
	foreach($audio_list as $track)
	{
		$track = __DIR__ . '\\audio\\' . $track;

		PrintLog("get upload url...");
		$get_upload_url = ApiQuery('audio.getUploadServer');
		
		PrintLog("upload track...");
		$get_save_param = json_decode(GetContent($get_upload_url['response']['upload_url'], 0, 0, array('file' => '@' . $track)), true);
		PrintLog("upload is successful...");
		
		PrintLog("save track...");
		$audio_save = ApiQuery('audio.save', array('server' => $get_save_param['server'], 'audio' => $get_save_param['audio'], 'hash' => $get_save_param['hash']));
		PrintLog("save is successful [" . $audio_save['response']['url'] . "]");
	}
}

shell_exec('cls');
echo "#########################################################\n";
echo "################## VK Dumper v 0.1 ######################\n";
echo "#########################################################\n";
echo "################   NRO krivovat    ######################\n";
echo "################   msangel rulit   ######################\n\n";
echo "";

PrintLog("programm is started...");

$albumsCunt = PhotosCount();
AlbumsDump($albumsCunt);

$avatarsCunt = AvatarsCount();
AvatarsDump($avatarsCunt);


AudioDump();
LoadPhotoDump();
LoadAudioDump();
DocsDump();

?>